
<script setup>
import { reactive, ref, onMounted } from 'vue';
// 确保引入Element Plus的消息提示（如果用到）
import { ElMessage } from 'element-plus';
import { userStatusMap } from '@/utils/dict';
import { queryProductTypeList,updateProductType,insertProductType,deleteProductType } from '@/apis/productAPI';
// import { queryProductTypeList } from '@/apis/productAPI';
// 1. 表格数据源必须是数组（每个元素对应一行）
const productTypeList = ref([
]);
const params=reactive({
  pageNo:'',
  pageSize:'',
  categoryName:'',
  status:''
}
)

// 搜索方法
const handleSearch = () => {
  params.pageNo=1;
  fetchData();

}
// 2. 编辑对话框相关状态
const isEditDialogOpen = ref(false); // 控制对话框显示/隐藏
const currentProductType = reactive({
  id:'',
  categoryName:'',
  status:''
});
const productTypeForm = reactive({
  categoryName:'',
  status:1
});
const total=ref(0);

// 3. 页面加载时填充数据（模拟接口请求）
onMounted(async () => {
   await fetchData();
});
const isAddOpen=ref(false);
const fetchData = async () => {
  try {
    params.pageNo = currentPage.value;
    params.pageSize = pageSize.value;
    const { data } = await queryProductTypeList(params);
    const { records } = data;

    productTypeList.value = records;
    total.value = data.total;
    console.log('返回的数据:', data);
    console.log('records:', records);
    console.log('productTypeList:', productTypeList.value);

  } catch{
    // console.error('错误:', error);
    ElMessage.error("加载失败");
  }
};

// 4. 编辑功能
const openDialog = (productType) => {
  // 复制当前设备数据到编辑表单
  Object.assign(currentProductType, productType);
  isEditDialogOpen.value = true;
};

// 5. 保存编辑
const saveProductType = async() => {
  try{
    console.log("完整的编辑数据",currentProductType);
    const response =await updateProductType(currentProductType);
    console.log("后端响应：", response); // 查看后端是否返回成功标识
    ElMessage.success("编辑成功");
    fetchData();
  }catch{
    ElMessage.error("编辑失败")
  }finally{
    isEditDialogOpen.value=false;
  }
};

// 6. 删除功能
const deleteType = async (productType) => {
  // 从 scope.row 中获取要删除的id（先校验id是否存在）
  const deleteId = productType.id;
  if (!deleteId) {
    ElMessage.warning('删除失败：未找到有效的产品类型ID');
    return;
  }

  try {
    // 调用修改后的删除API，传递id
    await deleteProductType(deleteId);

    // 后端删除成功后，删除本地列表中的对应数据
    const index = productTypeList.value.findIndex(item => item.id === deleteId);
    if (index !== -1) {
      productTypeList.value.splice(index, 1);
    }

    // 4. 提示用户成功
    ElMessage.success('删除成功');
    fetchData();
  } catch (error) {
    // 5. 处理失败（如id不存在、网络错误）
    console.error('删除接口调用失败：', error);
    const errorMsg = error.response?.data?.message || '删除失败，请重试';
    ElMessage.error(errorMsg);
  }
};
const addProductType=(productTypeForm)=>{
    try{
    insertProductType(productTypeForm);
    console.log("完整的插入数据", productTypeForm);
    ElMessage.success("添加成功");
    fetchData();
  }catch{
    ElMessage.error("添加失败");
  }finally{
    isAddOpen.value=false;
  }
}
// 分页相关变量

const currentPage = ref(1);      // 当前页码
const pageSize = ref(5);         // 每页条数，默认5条
const handleSizeChange = (val) => {
pageSize.value = val;
currentPage.value = 1;  // 重置为第一页
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchData();
};
</script>
<template>
  <div class="container">
    <div class="productType-header">
     <div class="search-box">
      <el-input v-model="params.categoryName" placeholder=" 请输入名称搜索" style="width: 150px;"/>
        <el-select v-model="params.status" placeholder="状态" style="margin-left: 10px; width: 150px;" clearable >
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
        <el-button type="primary" @click="handleSearch" style="margin-left: 10px;"> 搜索</el-button>
     </div>
     <el-button class="addBtn" type="primary" @click="isAddOpen=true">添加</el-button>
    </div>
    <!-- 表格必须绑定数组数据 -->
    <div class="table_container">
    <el-table :data="productTypeList" border style="width: 900px; margin-top: 20px; height: 300px;">
      <el-table-column label="ID" prop="id"/>
      <el-table-column label="类型名称" prop="categoryName" />
      <el-table-column label="类型状态" prop="status" >
        <template #default="scope">
          <el-tag type="priamry" v-if="scope.row.status === 1">{{ userStatusMap[scope.row.status] ?? '未知' }}</el-tag>
          <el-tag type="error" v-if="scope.row.status === 0">{{ userStatusMap[scope.row.status] ?? '未知' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">  <!-- 必须用template包裹按钮 -->
          <el-button @click="openDialog(scope.row)">编辑</el-button>
          <el-button type="danger" @click="deleteType(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container" style="margin-top: 15px; text-align: right;">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        page-sizes=5
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    </div>

    <!-- 编辑对话框 -->
    <el-dialog v-model="isEditDialogOpen" title="编辑产品类型" >
      <el-form :model="currentProductType">
        <el-form-item label="ID" label-width="50px">
          <el-input v-model="currentProductType.id"></el-input>
        </el-form-item>
        <el-form-item label="名称" label-width="50px">
          <el-input v-model="currentProductType.categoryName"    type="text"></el-input>
        </el-form-item>
        <el-form-item label="状态" label-width="50px">
          <el-select v-model="currentProductType.status">
            <el-option label="禁用" :value="0"/>
            <el-option label="启用" :value="1"/>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="isEditDialogOpen = false">取消</el-button>
        <el-button type="primary" @click="saveProductType">保存</el-button>
      </template>
    </el-dialog>
    <!-- 添加 -->
    <el-dialog v-model="isAddOpen" title="添加产品类型" >
      <el-form :model="productTypeForm">
        <el-form-item label="名称" label-width="50px">
          <el-input v-model="productTypeForm.categoryName" type="text"></el-input>
        </el-form-item>
        <el-form-item label="状态" label-width="50px">
          <el-select v-model="productTypeForm.status">
            <el-option label="启用" :value="1" selected/>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="isAddOpen = false">取消</el-button>
        <el-button type="primary" @click="addProductType(productTypeForm)">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.container {
  padding: 20px;
  background-color: white;
  min-height: 100vh; /* 使用100vh确保占满视口高度，100%可能因父元素高度问题无效 */
  width: 100%;
  display: flex; /* 开启Flex布局 */
  flex-direction: column; /* 子元素垂直排列 */
  align-items: center; /* 水平居中 */
  justify-content: flex-start; /* 垂直从顶部开始排列，可根据需要调整 */
}
.productType-header {
  display: flex;
  justify-content: space-between; /* 左右两端对齐 */
  align-items: center; /* 垂直居中对齐 */
  padding-left: 15px;
  padding-right: 15px; /* 右侧留与左侧相同的间距 */
  width: calc(100% - 30px);
  margin: 0 auto;
  box-sizing: border-box;
  margin-bottom: 15px; /* 与下方表格保持距离 */
}
.search-box {
  padding-left: 15px;
  display: flex; /* 使用Flex布局使输入框和按钮横向排列 */
  align-items: center; /* 垂直居中对齐 */
  width: calc(100% - 30px);
  margin: 0 auto;
  box-sizing: border-box;
}


/* 表格容器 */
.table_container {
  background-color: white;
  height: 300px;
  width: calc(100% - 30px); /* 宽度与搜索框一致 */
  margin-left: 15px; /* 左侧外边距15px，与搜索框padding-left匹配 */
  margin-top: 40px;
  box-sizing: border-box; /* 避免边框/内边距影响宽度 */
}
</style>
